import os
import sys

from corecode.bbox import IAR

import cv2
import dlib
import shutil
import corecode.api as corecode
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
np.set_printoptions(threshold=32, edgeitems=10)


def allFaces(image):

    face_locations = corecode.face_locations(image)

    aR = []

    for face_location in face_locations:
        top, right, bottom, left = face_location
        face_image = image[top:bottom, left:right]
        aR.append([face_image, face_location])
    return aR



def compare_faces(known_face_encodings, face_encoding_to_check, tolerance=0.5):
    """
    Compare a list of face encodings against a candidate encoding to see if they match.

    :param known_face_encodings: A list of known face encodings
    :param face_encoding_to_check: A single face encoding to compare against the list
    :param tolerance: How much distance between faces to consider it a match. Lower is more strict. 0.6 is typical best performance.
    :return: A list of True/False values indicating which known_face_encodings match the face encoding to check
    """
    return (corecode.face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)

def frange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step


cwd = os.getcwd()

sys_a = sys.argv[1]
sys_b = sys.argv[2]

cv_a = cv2.imread(sys_a)
cv_b = cv2.imread(sys_b)


if sys_a is None:
        print ('Image (a) is not an image')
        sys.exit(1)
if sys_b is None:
        print ('Image (b) is not an image')
        sys.exit(1)

if str(type(cv_a)) == "<type 'NoneType'>":
        print ('Image (a) is not an image')
        sys.exit(1)
if str(type(cv_b)) == "<type 'NoneType'>":
        print ('Image (b) is not an image')
        sys.exit(1)

sf_a = IAR(sys_a)
sf_b = IAR(sys_b)


nsf_a  = np.array(sf_a)
nsf_b  = np.array(sf_b)


a_face_encoding = corecode.face_encodings(nsf_a)[0]
b_face_encoding = corecode.face_encodings(nsf_b)[0]

#Bundles the main encoding
known_faces = [
    a_face_encoding,
    b_face_encoding
]


allRS = []
#The main ranking system.
for i in frange(0.0,  1.0,  0.1):
    results = compare_faces([a_face_encoding], b_face_encoding, i)
    isl = str(i)
    lis = len(isl)
    if ( lis < 5):
       allRS.append("{} @ tolerance level {}".format(results, i))
       print ("{} @ tolerance level {}".format(results, i))

    elif (lis > 5) and ( isl.endswith('4') ):
       allRS.append("{} @ tolerance level {}".format(results, str(i)[0:3]))

       print ("{} @ tolerance level {}".format(results, i))
    elif (lis > 5) and ( isl.endswith('9') ):
       allRS.append("{} @ tolerance level {}".format(results, str(i+0.1)[0:3]))
       print ("{} @ tolerance level {}".format(results, i+0.1))

#The plotting function
ff, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10,6))
ff.suptitle('Person Comparison')
ff.subplots_adjust(top=0.85)

ax1.imshow(sf_a)
ax1.set_title((sys_a.split('/')[-1]))
ax1.tick_params(labeltop='off', labelright='off', labelleft='off', labelbottom='off')
ax2.imshow(sf_b)
ax2.set_title((sys_b.split('/')[-1]))
ax2.tick_params(labeltop='off', labelright='off', labelleft='off', labelbottom='off')

ax3.set_title('Same person:')
ax3.plot([2, 1], 'r')
ax3.grid(False)
ax3.tick_params(labeltop='off', labelright='off', labelleft='off', labelbottom='off')
ax3.axis([0, 20, -len(allRS), 0])
for i, s in enumerate(allRS):
    ax3.text(0.1, -i-0.5, s, fontsize=10)


fd = (os.getcwd() + "/activefiles")
if not os.path.exists(fd): os.makedirs(fd)
plt.savefig('activefiles/pc-{}-{}.png'.format((sys_a.split('/')[-1]), (sys_b.split('/')[-1])))
plt.show()


